﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Memcached.ClientLibrary;
using System.Configuration;
using System.Collections;
using UserService.Entity;


namespace CustomCommon
{
    public class MemcacheHelper
    {
       
        private static readonly MyMemCachedClient mc = null;
        // private static readonly string MencacheHosts = ConfigurationManager.AppSettings["MencacheHosts"];
        private static string[] serverlist = { };// MencacheHosts.Split(new Char[] { ';' });// { "127.0.0.1:11211", "10.0.0.132:11211" };//一定要将地址写到Web.config文件中。
        static MemcacheHelper()
        {
            string _RootPath = AppDomain.CurrentDomain.GetData(".appPath").ToString();
            ExeConfigurationFileMap map = new ExeConfigurationFileMap();
            map.ExeConfigFilename = _RootPath + @"\bin\jczUserService.dll.config";
            Configuration config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
            string MencacheHosts = config.AppSettings.Settings["MencacheHosts"].Value;
            serverlist = MencacheHosts.Split(new Char[] { ';' });
            //初始化池
            SockIOPool pool = SockIOPool.GetInstance();
            pool.SetServers(serverlist);

            pool.InitConnections = 3;
            pool.MinConnections = 3;
            pool.MaxConnections = 5;

            pool.SocketConnectTimeout = 1000;
            pool.SocketTimeout = 3000;

            pool.MaintenanceSleep = 30;
            pool.Failover = true;

            pool.Nagle = false;
            pool.Initialize();

            // 获得客户端实例
            mc = new MyMemCachedClient();
            //mc.PoolName = "sessionId";
            mc.EnableCompression = false;
        }
        /// <summary>
        /// 向Memcache中写数据
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public static void Set(string key, object value)
        {
            mc.Set(key, value);
        }
        /// <summary>
        ///  向Memcache中写数据
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <param name="time">过期时间</param>
        public static void Set(string key, object value, DateTime time)
        {
            mc.Set(key, value, time);
        }
        /// <summary>
        /// 获取Memcahce中的数据
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static object Get(string key)
        {
            return mc.Get(key);
        }
        /// <summary>
        /// 删除Memcache中的数据
        /// </summary>
        /// <param name="key"></param>
        public static bool Delete(string key)
        {
            if (mc.KeyExists(key))
            {
                return mc.Delete(key);
            }
            return false;
        }

        #region 获取键数组对应的值
        /// <summary>
        /// 获取键数组对应的值
        /// </summary>
        /// <param name="serverlist">IP端口列表</param>
        /// <param name="poolName">连接池名称</param>
        /// <param name="keys">键列表</param>
        /// <returns>Hashtable键值对</returns>
        public static Hashtable GetCacheHt(ArrayList serverlist, string poolName, string[] keys)
        {
            //MemcachedClient mc = CreateServer(serverlist, poolName);
            return mc.GetMultiple(keys);
        }
        #endregion

        #region 获取键数组对应的值
        /// <summary>
        /// 获取键数组对应的值
        /// </summary>
        /// <param name="serverlist">IP端口列表</param>
        /// <param name="poolName">连接池名称</param>
        /// <param name="keys">键列表</param>
        /// <returns>值的数组(不包含键)</returns>
        public static object[] GetCacheList(string[] keys)
        {
            //MemcachedClient mc = CreateServer(serverlist, poolName);
            object[] list = mc.GetMultipleArray(keys);
            ArrayList returnList = new ArrayList();
            for (int i = 0; i < list.Length; i++)
            {
                if (list[i] != null)
                {
                    returnList.Add(list[i]);
                }
            }
            return returnList.ToArray();
        }
        #endregion

        #region 清空所有缓存
        /// <summary>
        /// 清空所有缓存
        /// </summary>
        /// <param name="serverlist">IP端口列表</param>
        /// <param name="poolName">连接池名称</param>
        /// <returns></returns>
        public static bool FlushAll()
        {
            //MemcachedClient mc = CreateServer(serverlist, poolName);
            return mc.FlushAll();
        }
        #endregion

        #region 遍历所有的sessionid
        private static ArrayList sessionidkeyArray = new ArrayList();
        /// <summary>
		/// Sets the pool that this instance of the client will use.
		/// The pool must already be initialized or none of this will work.
		/// </summary>
        public ArrayList SessionidKeyArray
        {
            get { return sessionidkeyArray; }
        }
        private static void getsessionid(Hashtable arr)
        {
            foreach (string key in arr.Keys)
            {
                //statsArray.Add(key);
                ArrayList values = (ArrayList)arr[key];
                foreach (string key2 in values)
                {
                    sessionidkeyArray.Add(key2);
                }
            }
            //return null;
        }
        public static void seachallsesionid()
        {
            sessionidkeyArray.Clear();
            Hashtable arr = mc.CommonStats(new ArrayList(serverlist), MyMemCachedClient.GetStats.Items, null);
            foreach (string key in arr.Keys)
            {
                //statsArray.Add(key);
                ArrayList values = (ArrayList)arr[key];
                foreach (string key2 in values)
                {
                    string[] info = key2.Split(':');
                    if (info.Length == 4)
                    {
                        string param = info[1] + " " + info[3];
                        Hashtable arrkeys = mc.CommonStats(new ArrayList(new string[] { key }), MyMemCachedClient.GetStats.CachedDump, param);
                        getsessionid(arrkeys);
                    }
                }
            }
        }
        public static bool SessionidToUserInfo_Boolean(string suerid)
        {
            seachallsesionid();
            foreach (string key in sessionidkeyArray)
            {
                if (key.Contains("jczuser-"))
                {
                    object obj = MemcacheHelper.Get(key);//根据key从Memcache中获取用户的信息
                    if (obj == null)
                    {
                        MemcacheHelper.Delete(key);
                        continue;
                    }
                    User userInfo = SerializerHelper.DeserializeToObject<User>(obj.ToString());
                    string s_user = userInfo.Id != null ? userInfo.Id.ToString() : "";
                    if (s_user.Equals(suerid))
                    {
                        return true;
                    }
                }
                else
                {
                    return false;
                }
               
            }
            return false;
        }
        #endregion
    }
}
